package com.lgl.scsheader.system.timer;

import com.lgl.scsapi.util.utils.Constants;
import com.lgl.scsheader.sameCityManage.service.SameCityCountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 系统统计类定时器
 */
@Component
public class SystemCountTimer {
    private Logger log = LoggerFactory.getLogger(SystemCountTimer.class);
    @Resource(name="sameCityCountService")
    private SameCityCountService sameCityCountService;
    @Resource
    private RedisTemplate redisTemplate;

    //保存上个月有多少个用户登录，并删除3个月以前的数据，每个月1号0点2分执行
    @Scheduled(cron = "0 0 0 1 * ?")
    public void countUserLoginTimes(){
        log.info("开始保存上个月的用户登录次数");
        sameCityCountService.saveLoginOfAppUserNumLastMonth();
        log.info("开始删除3个月前的用户登录次数数据");
        Calendar calendar = Calendar.getInstance();
        int lastMonth = calendar.get(Calendar.MONTH),currentYear = calendar.get(Calendar.YEAR);
        //3月以前的月份，如现在是9月，则beforeThreeMonth是6月
        int beforeThreeMonth = lastMonth - 2;
        //如果当前时间是3月以前
        if (lastMonth < 3){
            beforeThreeMonth += 12;
            calendar.set(Calendar.YEAR,currentYear - 1);
        }
        calendar.set(Calendar.MONTH,beforeThreeMonth - 1);
        //获取3月以前的月份最多有多少天
        int before3MonthMaxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        List<String> before3MonthKeys = new ArrayList(before3MonthMaxDay);
        for (int btm = 1; btm <= before3MonthMaxDay; btm ++){
            before3MonthKeys.add(Constants.USER_LOGIN_SET_PRE + beforeThreeMonth + btm);
        }
        redisTemplate.delete(before3MonthKeys);
        log.info("3个月前的用户登录次数数据已删除完成，before3MonthKeys=" + before3MonthKeys);
    }
}
